package com.gitee.zzh.demo.service.impl;

import com.gitee.zzh.common.ImageUtils;
import com.gitee.zzh.common.MyIOUtils;
import com.gitee.zzh.common.QrCodeInfo;
import com.gitee.zzh.demo.service.QrCodeService;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class QrCodeServiceImpl implements QrCodeService {
    /**
     * 生成渐变色的二维码：根据文本内容生成或者根据矩阵数据生成
     */
    public void createQrCode(QrCodeInfo qrCodeInfo) {
        BitMatrix bitMatrix = getBitMatrixL(qrCodeInfo);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
//        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                // 二维码颜色（RGB）
                int num1 = (int) (50 - (50.0 - 13.0) / bitMatrix.getHeight()
                        * (y + 1));
                int num2 = (int) (165 - (165.0 - 72.0) / bitMatrix.getHeight()
                        * (y + 1));
                int num3 = (int) (162 - (162.0 - 107.0) / bitMatrix.getHeight() * (y + 1));
                Color color = new Color(num1, num2, num3);
                int colorInt = color.getRGB();
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y)? colorInt : 0xFFFFFFFF);
            }
        }
        try(OutputStream outputStream = new FileOutputStream(qrCodeInfo.getQrCodePath())) {
            ImageIO.write(bufferedImage, "jpeg", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 矩阵字符串写入文件
     */
    @Override
    public void writeMatrixStrToFile(QrCodeInfo qrCodeInfo, String matrixStrPath) {
        //保存最小的字符串
        qrCodeInfo.setMulti(1);
        BitMatrix bitMatrix = getBitMatrixL(qrCodeInfo);
        String matrixString = ImageUtils.getMatrixString(bitMatrix);
        MyIOUtils.createOrClear(matrixStrPath);
        MyIOUtils.append(matrixStrPath, matrixString);
    }
    /**
     * 生成矩阵：根据文本内容生成
     */
    private BitMatrix getBitMatrixL(QrCodeInfo qrCodeInfo) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//内容所使用字符集编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);//纠错级别（L 7%、M 15%、Q 25%、H 30%）
        hints.put(EncodeHintType.MARGIN, qrCodeInfo.getQrCodeMargin());//设置二维码边的空度，非负整数
        hints.put(EncodeHintType.QR_VERSION, qrCodeInfo.getQrCodeVersion()); //1~40,值越大越密，信息量越大
        try {
            int width = qrCodeInfo.getTransformQrCodePix();
            return multiFormatWriter.encode(qrCodeInfo.getQrCodeContent(),
                    BarcodeFormat.QR_CODE, width, width, hints);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 识别二维码图片对应的文本
     */
    @Override
    public String getQrCodeContent(String path) {
        BufferedImage bufferedImage = null;
        try {
            InputStream inputStream = new FileInputStream(path);
            bufferedImage = ImageIO.read(inputStream);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");//内容所使用字符集编码
        try {
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            return result.getText();
        } catch (NotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 用矩阵字符串生成二维码
     */
    @Override
    public void createQrCodeFromMatrixStr(String path, String matrixStrPath, int scale) {
        String multiMatrixStr = ImageUtils.getMultiMatrixString(MyIOUtils.getText(matrixStrPath), scale);
        /*生成矩阵：根据字符串生成*/
        String[] rows = multiMatrixStr.split("\n");
        BitMatrix bitMatrix = new BitMatrix(rows.length, rows.length);
        for (int i = 0; i < rows.length; i++) {
            String[] cols = rows[i].split("");
            for (int j = 0; j < cols.length; j++) {
                if("1".equals(cols[j])) {
                    bitMatrix.set(i, j);
                }
            }
        }
        /*生成二维码*/
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        try(OutputStream outputStream = new FileOutputStream(path)) {
            ImageIO.write(bufferedImage, "jpeg", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
